package com.lab303.powerproject.controller;


import com.lab303.powerproject.entity.Device;
import com.lab303.powerproject.entity.AdditionalProperties;
import com.lab303.powerproject.entity.ElectricityPrice;
import com.lab303.powerproject.repository.ElectricityPriceRepository;
import com.lab303.powerproject.service.DeviceService;
import com.lab303.powerproject.service.PropertyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Controller
@RequestMapping("property")
public class PropertyController {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private PropertyService propertyService;

    @Autowired
    private ElectricityPriceRepository er;


    /**
     * 更新设备的附加属性
     * @param deviceId
     * @param request
     * @return
     */
    @PostMapping("/update/{device_id}")
    public String propertyUpdate(@PathVariable("device_id") Integer deviceId, HttpServletRequest request){

        String[] propertyId = request.getParameterValues("propertyId");
        String[] propertyName = request.getParameterValues("propertyName");
        String[] propertyValue = request.getParameterValues("propertyValue");
        Device deviceById = deviceService.findDeviceById(deviceId);
        List<AdditionalProperties> propertyList = new ArrayList<>();
        if(propertyId==null){
            for(int i =0 ; i< propertyName.length;i++){
                AdditionalProperties property = new AdditionalProperties(propertyName[i],propertyValue[i]);
                property.setDevice(deviceById);
                propertyList.add(property);
            }
        }else {
            for (int i =0 ; i< propertyId.length;i++){
                AdditionalProperties property = new AdditionalProperties(propertyName[i],propertyValue[i]);
                property.setPropertyId(Integer.parseInt(propertyId[i]));
                property.setDevice(deviceById);
                propertyList.add(property);
            }
            for(int j  = propertyId.length;j<propertyName.length;j++){
                AdditionalProperties property = new AdditionalProperties(propertyName[j],propertyValue[j]);
                property.setDevice(deviceById);
                propertyList.add(property);
            }
        }
        deviceById.setPropertyList(propertyList);
        deviceService.saveAndUpdateProperties(deviceById);
        return "redirect:/device/get/"+deviceId;
    }

    /**
     * 删除设备的附加属性
     * @param propertyId
     * @return
     */
    @GetMapping("/delete/{id}")
    @ResponseBody
    public String deleteProperty(@PathVariable("id") Integer propertyId){
        propertyService.deletePropertyById(propertyId);
        return "success";
    }

    /**
     * 跳转电价修改界面
     * @param model
     * @return
     */
    @GetMapping("/editElePrice")
    public String editElectricityPrice(Model model){
        ElectricityPrice price = er.findById(1).get();
        String[] split = price.getPrice().split(",");
        model.addAttribute("priceList",split);
        return "elePriceEdit";
    }

    /**
     * 修改电价
     * @param request
     * @return
     */
    @PostMapping("/updateElePrice")
    public String updateElectricityPrice(HttpServletRequest request){
        String[] priceList = request.getParameterValues("priceList");
        StringBuilder sb = new StringBuilder();
        for (int i = 0 ;i<priceList.length;i++){
            sb.append(priceList[i]);
            if (i<priceList.length-1) sb.append(",");
        }
        ElectricityPrice electricityPrice = new ElectricityPrice();
        electricityPrice.setId(1);
        electricityPrice.setPrice(sb.toString());
        er.save(electricityPrice);
        return "redirect:/property/electricityPrice";
    }


    /**
     * 查看电价
     * @param model
     * @return
     */
    @GetMapping("/electricityPrice")
    public String viewElectricityPrice(Model model){
        ElectricityPrice price = er.findById(1).get();
        List<Float[]> priceList = getPrice(price);
        List<Map> list = new ArrayList<>();
        float max = Float.MIN_VALUE;
        float min = Float.MAX_VALUE;
        for (Float[] p : priceList){
            max = Float.max(max,p[2]);
            min = Float.min(min,p[2]);
        }
        StringBuilder high = new StringBuilder();
        StringBuilder low = new StringBuilder();
        StringBuilder mid = new StringBuilder();
        for (Float[] p : priceList){
            Map<String,Object> map = new HashMap();
            String str = p[0].intValue() + ":00-" + p[1].intValue() + ":00";
            map.put("name",str);
            map.put("price",p[2]);
            if (max==p[2].floatValue()){
                high.append(str);
                high.append(" ");
            }
            else if (min==p[2].floatValue()){
                low.append(str);
                low.append(" ");
            }else {
                mid.append(str);
                mid.append(" ");
            }
            list.add(map);
        }
        model.addAttribute("priceList",list);
        model.addAttribute("high",high.toString());
        model.addAttribute("low",low.toString());
        model.addAttribute("mid",mid.toString());
        return "elePrice";
    }

    /**
     * 处理电价数据，使之按照要求显示
     * @param price
     * @return
     */
    private List<Float[]> getPrice(ElectricityPrice price){
        String s = price.getPrice();
        String[] split = s.split(",");
        Map<String,List<Integer>> map = new HashMap();
        for (int i = 0;i<split.length;i++){
            if(map.containsKey(split[i]))
                map.get(split[i]).add(i);
            else{
                List list = new ArrayList();
                list.add(i);
                map.put(split[i],list);
            }
        }
        Iterator<Map.Entry<String, List<Integer>>> iterator = map.entrySet().iterator();
        List<Float[]> res = new ArrayList<>();
        while (iterator.hasNext()){
            Map.Entry<String, List<Integer>> entry = iterator.next();
            System.out.print(entry.getKey()+"  ");
            entry.getValue().forEach(a-> System.out.print(a+" "));
            System.out.println();
            String key = entry.getKey();
            List<Integer> entryValueList = entry.getValue();
            Iterator<Integer> integerIterator = entryValueList.iterator();
            int begin = integerIterator.next();
            int end = begin;
            if (!integerIterator.hasNext()) res.add(new Float[]{Float.valueOf(begin), (Float.valueOf(end)+1.0f)%24,Float.parseFloat(key)});
            while (integerIterator.hasNext()){
                Integer next = integerIterator.next();
                if (next==end+1){
                    end++;
                }else {
                    res.add(new Float[]{Float.valueOf(begin), (Float.valueOf(end)+1.0f)%24,Float.parseFloat(key)});
                    begin = end = next;
                }
                if (!integerIterator.hasNext()){
                    res.add(new Float[]{Float.valueOf(begin), (Float.valueOf(end)+1.0f)%24,Float.parseFloat(key)});
                }
            }
        }
        return res;
    }
}
